//
//  CommonService.swift
//  LeGou
//
//  Created by lxm on 2022/7/23.
//

import Foundation
import RxSwift
class CommonService {
    
    static var permissionKey = "permissionKey"
    
    private init() {
        checkIsOk = UserDefaults.standard.bool(forKey: CommonService.permissionKey)
    }
    
    var checkVersionDisposeBag = DisposeBag()
    
    // 城市信息
    var cityInfo : [CommonModels.CityModel]?
    
    static let shared = CommonService()
    
    let CITY_JSON_KEY = "CITY_JSON_KEY"
    
    var cityDisposeBag = DisposeBag()
    
    var appInitBag = DisposeBag()
    
    var appInfo = [String : Any]()
    
    // 审核OK
    var checkIsOk = false
    
    
    func getCityInfo(ok : @escaping (_ info : [CommonModels.CityModel]?)->()) {
        cityDisposeBag = DisposeBag()
        if let cityInfo = cityInfo {
            ok(cityInfo)
        } else {
            let path = Bundle.main.path(forResource: "city", ofType: "json")
            let url = URL(fileURLWithPath: path!)
            do {
                let data = try Data(contentsOf: url)
                let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
                let jsonArr = jsonData as! NSArray
                cityInfo = JSONDeserializer<CommonModels.CityModel>.deserializeModelArrayFrom(array: jsonArr)?.compactMap({$0})
                ok(cityInfo)
            } catch let error as Error? {
                print("读取本地数据出现错误!",error!)
                ok(nil)
            }
        }
//        if let json = UserDefaults.standard.object(forKey: CITY_JSON_KEY) as? String, let rp = [CommonModels.CityModel].deserialize(from: json) {
//            // 从本地缓存中读取
//            self.cityInfo = rp.compactMap({$0})
//        } else {
//            CommonAPI.cityList.rxRequest(type: [CommonModels.CityModel].self).subscribe(onNext:{ [unowned self] resp in
//                ok(resp)
//                self.cityInfo = resp
//                if let json = resp.toJSONString() {
//                    // 缓存到本地
//                    UserDefaults.standard.setValue(json, forKey: CITY_JSON_KEY)
//                }
//            }) { _ in
//                ok(nil)
//            }.disposed(by: cityDisposeBag)
//        }
    }
    
    func appInit() {
        appInitBag = DisposeBag()
        getCityInfo { info in
            
        }
        
        CommonAPI.appInitInfo.rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            self.appInfo = resp
            let v = JSON(resp)["thev"].stringValue
            if v.count > 0 {
                if v == THE_V {
                    UserDefaults.standard.set(false, forKey: CommonService.permissionKey)
                    checkIsOk = false
                } else {
                    UserDefaults.standard.set(true, forKey: CommonService.permissionKey)
                    checkIsOk = true
                }
            }
        }).disposed(by: appInitBag)
    }
    
    func goWeb(type : ArticleType) {
        let vc = ArticleDetail()
        vc.type = type
        UIApplication.zm.visibleNavigationController().pushViewController(vc, animated: true)
    }
    
    func wxServiceStr() -> String {
        return JSON(self.appInfo)["serviceWx"].stringValue
    }
    
    /// 弹出联系客服微信弹框
    func showContactService() {
//        let wx = wxServiceStr()
//        guard wx.count > 0 else {
//            ZMToast.showToast(title: "没有获取到客户微信号")
//            return
//        }
//        let v = ZMUtil.loadNibViewFullScreen(nibName: ServiceWx.self)
//        v.wxLabel.text = wx
//        APPWindow?.addSubview(v)
        goWeb(type: .contactService)
    }
    
    
    /// 弹出交易密码输入
    /// - Parameter compete: 交易密码输入完成回调
    func showPsdInput(title : String? = nil,
                      money : String,
                      left : String,
                      center : String? = nil,
                      right : String,
                      type : Int = 0,
                      subTitle : String? = nil,
                      compete : @escaping ((_ psd : String, _ close: @escaping ((_ ok : Bool)->()))->()), pushtoOther : (()->())? = nil) {
//        if let user = ZMAppShareData.share.user, user.hasTradePwd == false {
//            // 没有设置交易密码
//            showNotSetThePsd()
//            if let pushtoOther = pushtoOther {
//                pushtoOther()
//            }
//            return
//        }
        let v = ZMUtil.loadNibView(nibName: TransactionCodeInputView.self)
        v.frame = CGRect(x: 0, y: 0, width: SCREEN_W, height: SCREEN_H)
        v.setprice(money: money, left: left, right: right)
        v.compete = { [weak v] psd in
            compete(psd, { ok in
                if ok {
                    v?.removeFromSuperview()
                } else {
                    v?.clear()
                }
            })
        }
        if type == 1 {
            v.unit.isHidden = true
            if let subTitle = subTitle {
                v.pointLabel.text = subTitle
            }
        } else {
            v.pointLabel.isHidden = true
        }
        if let title = title {
            v.titleLabel.text = title
        }
        if let center = center {
            v.centerTip.text = center
            v.centerTip.isHidden = false
        } else {
            v.centerTip.isHidden = true
        }
        v.forgetClick = { [weak v] in
            v?.removeFromSuperview()
            router.push("xm://main/safe/setPayPwd")
            if let pushtoOther = pushtoOther {
                pushtoOther()
            }
        }
        APPWindow?.addSubview(v)
    
        v.beginEdit()
    }
}


